/*
 * @author zzr
 * @date: 2025/05/07  16:17
 * @description: 复习实现一下阻塞队列
 */

class MyBlockingQueue2 {

    private String[] elems = null;
    private int head;
    private int tail;
    private int size; // 记录数组中的元素个数
    Object locker = new Object();

    public MyBlockingQueue2(int capacity) {
        this.elems = new String[capacity];
    }

    public void put(String elem) throws InterruptedException {
        synchronized (locker) {

            while (size >= elems.length) {
                // 队列满了 应该阻塞
                locker.wait();
            }
            elems[tail] = elem;
            tail++;
            size++;
            if (tail >= elems.length) {
                tail = 0;
            }
            locker.notify();
        }
    }

    public String take() throws InterruptedException {

        String elem;
        synchronized (locker) {

            while (0 == size) {
                // 队列为空
                // 阻塞等待
                locker.wait();
            }
            elem = elems[head];
            head++;
            size--;
            if (head >= elems.length) {
                head = 0;
            }
            locker.notify();
        }
        return elem;
    }
}
public class Demo6 {
    public static void main(String[] args) {

        MyBlockingQueue2 myBlockingQueue2 = new MyBlockingQueue2(1000);

        Thread t1 = new Thread(() -> {
            int n = 1;
            while (true) {
                try {
                    myBlockingQueue2.put(n + "");
                    System.out.println("添加元素" + n);
                    n++;
                    Thread.sleep(500);

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        Thread t2 = new Thread(() -> {
            while (true) {
                try {
                    String ret = myBlockingQueue2.take();
                    System.out.println("消耗元素" + ret);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        t1.start();
        t2.start();
    }
}
